package net.maku.kyy.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.common.utils.Result;
import net.maku.framework.operatelog.annotations.OperateLog;
import net.maku.framework.operatelog.enums.OperateTypeEnum;
import net.maku.kyy.service.KyyForumService;
import net.maku.kyy.query.KyyForumQuery;
import net.maku.kyy.vo.KyyForumVO;
import net.maku.tencentsms.service.TencentReportService;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;

import java.util.List;

/**
 * 圈子表
 *
 * @author MAKU babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@RestController
@RequestMapping("/kyy/forum")
@Tag(name = "圈子表")
@AllArgsConstructor
public class KyyForumController {
    private final KyyForumService kyyForumService;

    @Autowired
    private TencentReportService tencentReportService;

    @GetMapping("page")
    @Operation(summary = "分页")
    public Result<PageResult<KyyForumVO>> page(@ParameterObject @Valid KyyForumQuery query) {
        PageResult<KyyForumVO> page = kyyForumService.page(query);
        return Result.ok(page);
    }


    /**
     * 帖子浏览量加一
     * @param id
     * @return
     */
    @GetMapping("/num1/add")
    public Result<String> updateNum1(Integer id) {
        kyyForumService.updateNum1(id);
        return Result.ok();
    }


    /**
     * 点赞+1
     * @param id
     * @return
     */
    @GetMapping("/num3/add")
    public Result<String> updateNum3(Integer id) {
        kyyForumService.updateNum3(id);
        return Result.ok();
    }

    /**
     * 点赞-1
     * @param id
     * @return
     */
//    @GetMapping("/num3/reduce")
    public Result<String> updateNum3Reduce(Integer id) {
        kyyForumService.updateNum3Reduce(id);
        return Result.ok();
    }

    @GetMapping("/page/me")
    public Result<PageResult<KyyForumVO>> pageMe(@ParameterObject @Valid KyyForumQuery query) {
        PageResult<KyyForumVO> page = kyyForumService.pageForumMe(query);
        return Result.ok(page);
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    public Result<KyyForumVO> get(@PathVariable("id") Long id) {
        KyyForumVO data = kyyForumService.get(id);

        return Result.ok(data);
    }

    @CrossOrigin
    @GetMapping("/getOpenID")
    public Result<String> getAppID(String code) {
        String result = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session?appid="
                + "wxeb51ae4d4753d3bd" + "&secret=" + "74706deff320b23a81c3b24f7a3f4b57"
                + "&js_code=" + code + "&grant_type=authorization_code");
        String openid = JSON.parseObject(result).getString("openid");
        return Result.ok(openid);
    }

    @CrossOrigin
    @GetMapping("/checkText")
    public Result<String> checkText(String text, String openid) {
        String result = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxeb51ae4d4753d3bd&secret=74706deff320b23a81c3b24f7a3f4b57");
        String access_token = JSON.parseObject(result).getString("access_token");
        JSONObject bodyData = new JSONObject();
        bodyData.put("content", text);
        bodyData.put("version", 2);
        bodyData.put("scene", 2);
        bodyData.put("openid", openid);
        String result2 = HttpUtil.post("https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + access_token, bodyData.toString());
        String suggest = JSON.parseObject(result2).getJSONObject("result").getString("suggest");
        return Result.ok(suggest);
    }

    @PostMapping("/push")
    @Operation(summary = "保存")
    @OperateLog(type = OperateTypeEnum.INSERT)
    public Result<String> push(@RequestBody KyyForumVO vo) {
/*// 发起HTTP GET请求，获取微信接口的access_token
        String result = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxeb51ae4d4753d3bd&secret=74706deff320b23a81c3b24f7a3f4b57");

// 解析返回的JSON字符串，提取出access_token
        String access_token = JSON.parseObject(result).getString("access_token");

// 创建一个新的JSONObject对象，用于构建请求体
        JSONObject bodyData = new JSONObject();

// 设置内容审核的版本号，这里设置为2
        bodyData.put("version", 2);

// 将标题、内容、标签2和游戏名称拼接在一起，作为待审核的内容
        bodyData.put("content", vo.getTitle() + vo.getContent() + vo.getTag2() + vo.getGamename());

// 设置内容审核的场景，这里设置为2
        bodyData.put("scene", 2);

// 设置用户的openid，用于标识用户
        bodyData.put("openid", vo.getOpenid());

// 发起HTTP POST请求，将请求体发送到微信的内容安全接口进行审核
        String result2 = HttpUtil.post("https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + access_token, bodyData.toString());

// 解析返回的JSON字符串，提取出审核结果中的建议（suggest）
        String suggest = JSON.parseObject(result2).getJSONObject("result").getString("suggest");

        if ("pass".equals(suggest)) {
            kyyForumService.save(vo);
            return Result.ok("发布成功");
        } else {
            return Result.ok("标题/内容/标签存在非法信息，如若再犯将永久封禁");
        }*/
//        System.out.println("vo = " + vo);

        String text= vo.getTitle() + vo.getContent() + vo.getTag1()+vo.getTag2() +vo.getTag3()+ vo.getGamename();
        System.out.println(text);
        JSONObject originalJson=tencentReportService.textReview(text);
        System.out.println("originalJson = " + originalJson);
        if (originalJson.getString("Label").equals("Normal")) {
            Result<String> save = save(vo);
            return save;
        }
        JSONObject chineseJson = tencentReportService.convertToChinese(originalJson);
        Result<String> error = Result.ok(chineseJson.toString());
        return error;
    }


    @PostMapping
    @Operation(summary = "保存")
    @OperateLog(type = OperateTypeEnum.INSERT)
    @PreAuthorize("hasAuthority('kyy:user')")
    public Result<String> save(@RequestBody KyyForumVO vo) {
        //
        kyyForumService.save(vo);
        return Result.ok("发布成功");
    }

    @PutMapping
    @Operation(summary = "修改")
    @OperateLog(type = OperateTypeEnum.UPDATE)
    @PreAuthorize("hasAuthority('kyy:user')")
    public Result<String> update(@RequestBody @Valid KyyForumVO vo) {
        kyyForumService.update(vo);

        return Result.ok();
    }

    @DeleteMapping
    @Operation(summary = "删除")
    @OperateLog(type = OperateTypeEnum.DELETE)
    @PreAuthorize("hasAuthority('kyy:user')")
    public Result<String> delete(@RequestBody List<Long> idList) {
        kyyForumService.delete(idList);
        return Result.ok();
    }


    @GetMapping("export")
    @Operation(summary = "导出")
    @OperateLog(type = OperateTypeEnum.EXPORT)
    @PreAuthorize("hasAuthority('kyy:user')")
    public void export() {
        kyyForumService.export();
    }


    /**
     * 获取点赞状态
     * @param id
     * @return true 已点赞 false 未点赞
     */
    @GetMapping("/like/style")
    @PreAuthorize("hasAuthority('kyy:user')")
    public Result<Boolean> getLikeStyle(Long id) {
        return Result.ok(kyyForumService.getLikeStyle(id));
    }



}